<template>
  <el-container>
	  <el-header>
	    <div class="report_header" ref="headerHeight">
	      <div class="report_header_left"></div>
	      <!-- <div style="width: 100px;display: flex;align-items: center;margin-left: 10px;">
	        <svg-icon class="primary" :icon-class="$route.meta.icon"/>
	        <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
	      </div> -->
	      <div style="display: flex;flex-direction: row;justify-content: space-between;width: 100%;">
	        <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px;justify-content: flex-end;">
	          <div class="report_header_date">
	            <el-date-picker
				  style="width: 100%;"
	              v-model="query.date"
	              value-format="yyyy-MM-dd"
	              type="daterange"
	              align="right"
	              unlink-panels
	              range-separator="至"
	              start-placeholder="开始日期"
	              end-placeholder="结束日期"
	              :picker-options="pickerOptions"
	            />
	          </div>
	          <div class="report_header_query">
	            <el-select v-model="supplierQuery" placeholder="择供应商" filterable  value-key="id" :filter-method="querySupplier" clearable @change="changeSupp">
	              <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item" >
	                <div style="display: flex">
	                  <span style="float: left;width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
	                  <span style="width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.phone }}</span>
	                  <div style="width: 200px;">
	                    <span style="color: #8492a6; font-size: 8px;">{{item.areaName}}{{item.address}}</span>
	                  </div>
	                </div>
	              </el-option>
	              <div style="display: flex;width: 100%;position: absolute;bottom: 0">
	                <div style="width: 50%;background-color: rgb(248,248,248);"></div>
	                <div class="elOption" @click="toSearchSupplier">搜索供应商</div>
	              </div>
	              <div style="height: 30px"></div>
	            </el-select>
	          </div>
	          <!--<div class="report_header_query"  style="width: 150px">-->
	           <!--<el-select v-model="query.status" placeholder="状态" clearable>-->
	             <!--<el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />-->
	           <!--</el-select>-->
	          <!--</div>-->
            <div class="report_header_query" style="width: 150px">
              <el-select v-model="query.paymentPluginId" clearable placeholder="结算方式">
                 <el-option label="现金" value="cashPayPlugin"></el-option>
                 <el-option label="月结" value="debtPayPlugin"></el-option>
                 <el-option label="代销" value="salePayPlugin"></el-option>
              </el-select>
            </div>
	        </div>
          <div>
	        <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryClick">查询</el-button>
	        <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="add()"
	          v-permission="['payable.add']">新增付款</el-button>
           <ExportList2Excel style='margin-top: 5px;' ref="exportList2Excel" @handleExport="handleExport" name="导出" />
          </div>
	      </div>
	    </div>
	  </el-header>
    <div class="pd10">
      <el-table ref="payableTable" v-loadMore="[Math.random(), 'payable-list']" :height="curHeight" :data="payableList" border stripe :span-method="totalLine">
        <el-table-column label="排序" align="center" type="index" width="50%" >
            <template slot-scope="scope">{{ scope.$index == payableList.length-1?'总计':scope.$index +1}}</template>
        </el-table-column>
        <el-table-column label="供应商名称" header-align="center" align="left" prop="supplierName" width="200"/>
        <el-table-column label="结算方式" header-align="center" align="left" prop="paymentPluginName" width="150"/>
        <el-table-column label="联系电话" header-align="center" align="center" prop="mobile" width="150"/>
        <el-table-column label="应付金额" header-align="center" align="right" prop="amount" width="120" />
        <el-table-column label="已付金额" header-align="center" align="right" prop="amountPaid" width="120" />
        <el-table-column label="未付金额" header-align="center" align="right" prop="restAmount" width="120"  />

        <el-table-column label="地址" header-align="center"  align="left" prop="dress"/>
        <el-table-column label="功能" align="center" width="80" >
          <template slot-scope="scope" v-if="scope.$index != payableList.length-1">
            <el-button v-permission="['transfer.add']" v-if="scope.row.status !== 2" type="primary" round size="mini" @click="showDialog(scope.row)">付款</el-button>
            <el-tag v-else type="success" >已付款</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadPayable" />
    </el-footer>

    <el-dialog
      title="查找供应商"
      :visible.sync="supplierVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="supplierClose">
      <div style="position: relative;height: 63vh;overflow: auto">
        <supplierTable :key="times"  @doubleSupplier="doubleSupplier"></supplierTable>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>


 import ExportList2Excel from "@/components/ExportList2Excel";
import {mapGetters} from 'vuex'
import {EventBus} from '@/api/eventBus'
import supplierTable from '../../components/SupplierTable/supplierList'
import loadMore from '@/utils/loadMore.js'
import {selectCountList,summary} from '@/api/payable'
import { list as supplierList } from '@/api/supplier'
import Pagination from '@/components/Pagination'
import permission from '@/directive/permission/index.js' // 权限判断指令
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import {
    getMenuTree
  } from '@/api/sysMch.js'
  import utils from '../../utils/utils.js'
export default {
  name: 'payable-list',
  directives: { loadMore, permission ,elDragDialog},
  components: { Pagination,supplierTable,ExportList2Excel},
  filters: {
    watchStatus(val) {
      if (val === 0) {
        return '待付款'
      } else if (val === 1) {
        return '部份付款'
      } else if (val === 2) {
        return '已完成'
      }
    }
  },
  computed: {
    ...mapGetters([
      'scopeType'
    ])
  },
  data() {
    return {
              printing:5000,//打印数量设置
      payableList: [],
      queryType: true,
      supplierQuery:'',
      total: 0,
      times:'',
      pageNum: 1,
      supplierVisible:false,
      pageSize: 20,
      dialogVisible: false,
      supplierName: '',
      supplierOptions: [],
       isWaterShow: false,
      supplierMark: false,
      statusOptions: [
        { label: '全部', value: '' },
        { label: '待付款', value: 0 },
        // { label: '部份付款', value: 1 },
        { label: '已完成', value: 2 }
      ],
      paymentOptions: [
        { label: '现金', value: 'cashPayPlugin' },
        { label: '转账', value: 'debtPayPlugin' }
      ],
      paymentPluginName: '',
      maxAmount: 0,
      collectAmount: '',
      form: {},
      payableSupplierList: [],
      selectionChange: [],
      saveClicked: false,
      curHeight: null,
      queryClicked: false,
      resetClicked: false,
      query: {
        supplierId: '',
        date: [],
        status: '',
        paymentPluginId:''
      },
      pickerOptions: {// 时间快捷选择
        shortcuts: [{
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.loadPayable()
    this.querySupplier()
    EventBus.$on('payable-add', res => { // 监听新增完毕
        // 更新列表数组
      this.loadPayable();
    });
  },
  mounted() {
    this.comeIn()
    this.beforeMount()
  },
  methods: {
       handleExport() {
        let _this = this
        var loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let data = {}
        data.tHeader = ["供应商名称","结算方式", "联系电话","应收金额","已付金额", '未收金额','地址']
        data.filterVal = ["supplierName","paymentPluginName","mobile","amount","amountPaid",'restAmount','address']
        data.filename = "应付款汇总表";

         const keyword = Object.assign({}, this.query)
         if(utils.isNull(keyword.date)){
           keyword.date = []
         }
        const params = new URLSearchParams()
        params.append('pageNum', this.pageNum)
        params.append('pageSize', this.printing)
         params.append('supplierId', keyword.supplierId)
         params.append('paymentPluginId', keyword.paymentPluginId)
         params.append('startDate', keyword.date.length > 0 ? keyword.date[0] : '')
         params.append('endDate', keyword.date.length > 0 ? keyword.date[1] : '')
        selectCountList(params).then(res => {
          data.list = res.data.data
         summary(params).then(res=>{
          if(res.data[0]!=null&&res.data.length>0){
             this.$set(res.data[0],"supplierId","合计")
            data.list.push(res.data[0])
            _this.$refs.exportList2Excel.handleDownload(data);
            loading.close();
            }
         })
         if(data.list.length==this.printing){
            this.pageNum++
             console.log(this.pageNum);
             this.handleExport()
          }
          else{
            return;
          }
        }).catch(error => {
          _this.$refs.exportList2Excel.unlockLoading()
          loading.close();
          console.log('error!!')
        })
      },

    doubleSupplier(data){
      this.supplierQuery=data.name
      this.query.supplierId=data.id
      this.supplierVisible=false
    },
    supplierClose(){
      this.supplierVisible=false
    },
    toSearchSupplier(){
      this.times=new Date().getSeconds()
      this.supplierVisible=true
    },
    changeSupp(val){
      if(!utils.isNull(val)){
        this.supplierQuery=val.name
        this.query.supplierId=val.id
      }else{
        this.query.supplierId=''
      }

    },
      summaryClick() {
        var _this = this
        const keyword = Object.assign({}, this.query)
        if(utils.isNull(keyword.date)){
          keyword.date = []
        }
        const params = new URLSearchParams()
        params.append('supplierId', keyword.supplierId)
        params.append('paymentPluginId', keyword.paymentPluginId)
        params.append('startDate', keyword.date.length > 0 ? keyword.date[0] : '')
        params.append('endDate', keyword.date.length > 0 ? keyword.date[1] : '')
        summary(params).then(response => {
           if(response.data[0]!=null&&response.data.length>0){
           _this.payableList.push(response.data[0])
        }
        }).catch(error => {})
      },
    loadPayable() {
      let _this = this;
      const keyword = Object.assign({}, this.query)
      if(utils.isNull(keyword.date)){
        keyword.date = []
      }
      const params = new URLSearchParams()
      params.append('pageNum', this.pageNum)
      params.append('pageSize', this.pageSize)
      params.append('supplierId', keyword.supplierId)
      params.append('paymentPluginId', keyword.paymentPluginId)
      params.append('startDate', keyword.date.length > 0 ? keyword.date[0] : '')
      params.append('endDate', keyword.date.length > 0 ? keyword.date[1] : '')
      return new Promise((resolve, reject) => {
        selectCountList(params).then(res => {
            console.log(res)
          _this.total = res.data.total
          _this.payableList = res.data.data;
//          _this.payableList = res.data.data.(item => {
//            item.amount = Number(item.amount).toFixed(2)
//            item.amountPaid = Number(item.amountPaid).toFixed(2)
//            item.restAmount = (item.amount - item.amountPaid).toFixed(2)
//          })
          _this.summaryClick()
          resolve()
        })
      })
    },
    showDialog(data) {

         this.$router.push({
          path:"/payable/add",
          query:{
            paymentPluginId:'cashPayPlugin',
            paymentPluginName:'现金',
            supplierId:data.supplierId,
            supplierName:data.supplierName ,
            id:data.id
          }
        })
    },

    querySupplier(query) {
      clearTimeout(this.supplierMark)
      this.supplierMark = setTimeout(() => {
        supplierList({ name: query }).then(res => {
          this.supplierOptions = res.data.data
        }).catch(err => { console.log(err) })
      }, 500)
    },
    queryClick() {
      this.queryClicked = true
      this.pageNum = 1
      this.loadPayable().then(() => { this.queryClicked = false })
    },
    resetClick() {
      this.supplierQuery=''
      this.resetClicked = true
      this.query.supplierId = ''
      this.query.date = []
      this.query.status = ''
      this.pageNum = 1
      this.loadPayable().then(() => { this.resetClicked = false })
    },
    beforeMount() {
      window.onresize = () => {
        return (() => {
          const h = document.documentElement.clientHeight || document.body.clientHeight
          if (this.queryType === false) {
            this.curHeight = h - 266// 减去页面上固定高度height
          } else {
            this.curHeight = h - 220// 减去页面上固定高度height
          }
        })()
      }
    },
    comeIn() {
      const h = document.documentElement.clientHeight || document.body.clientHeight
      this.curHeight = h - 220// 减去页面上固定高度height
    },
    chooseClick() {
      this.queryType = !this.queryType
      const h = document.documentElement.clientHeight || document.body.clientHeight
      if (this.queryType === false) {
        this.curHeight = h - 266// 减去页面上固定高度height
      } else {
        this.curHeight = h - 220// 减去页面上固定高度height
      }
    },
    add(){
      this.$router.push({
        path: '/payable/add'
      })
    },
    totalLine({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        var _this = this
        if (rowIndex === _this.payableList.length - 1) {
          if (columnIndex === 0) {
            return {
              rowspan: 1,
              colspan: 4
            };
          } else if (columnIndex === 1 || columnIndex === 2 || columnIndex === 3) {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      },
  }
}
</script>

<style scoped>

  body .el-table th.gutter {
    display: table-cell !important
  }
  .elOption{
       background-color: #909399;
       color:white ;
       text-align: center;
       display: flex;
       align-items: center;
       justify-content: center;
       width: 50%;
       height: 40px
     }
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
  .report_header_date {
      margin-left: 10px;
      width: 250px;
      margin-top: 5px;
    }
</style>
